package com.zimmur.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zimmur.common.ReturnJsonEntity;
import com.zimmur.common.StatusCodeEnum;
import com.zimmur.model.goods.Goods;
import com.zimmur.model.goods.GoodsSize;
import com.zimmur.model.order.Order;
import com.zimmur.model.order.view.ReceiveOrderListModel;
import com.zimmur.model.order.view.ReceiveOrderModel;
import com.zimmur.service.goods.IGoodsService;
import com.zimmur.service.goods.IGoodsSizeService;
import com.zimmur.service.order.IOrderService;
import com.zimmur.tenpay.util.WechatUtil;

/**
 * 订单处理
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping(value = "/restful/order")
public class OrderController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(OrderController.class);

	@Resource(name = "orderServiceImpl")
	private IOrderService orderService;
	@Resource
	private IGoodsSizeService goodsSizeService;
	@Resource
	private IGoodsService goodsService;
	@Resource(name = "taskExecutor")
	private ThreadPoolTaskExecutor taskExecutor;

	@Value("#{spingMvcProperties['System.GuestId']}")
	private String guessUserId;

	/**
	 * 创建订单
	 * 
	 * @param 商品ID:
	 *            orderCollocations[0].goodsId<br/>
	 *            商品色码: orderCollocations[0].goodsColor<br/>
	 *            是否预售商品: orderCollocations[0].isPrepay<br/>
	 *            商品尺码: orderCollocations[0].goodsSize<br/>
	 *            商品数量: orderCollocations[0].goodsNum<br/>
	 *            是否开票: isInvoice<br/>
	 *            开票姓名: invoiceName<br/>
	 *            送货地址ID: addressId<br/>
	 *            快递编号: expressCode<br/>
	 *            支付方式 wxpay/alipay: payMethod<br/>
	 *            积分兑换: pointJe<br/>
	 *            快递费用: expressFee<br/>
	 *            优惠券ID：couponIds 备注:remark<br/>
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public ReturnJsonEntity createOrder() {
		ReturnJsonEntity returnJsonEntity = new ReturnJsonEntity();
		StatusCodeEnum statusCodeEnum = StatusCodeEnum.CODE100000;
		// 游客身份验证
		if (String.valueOf(getTokenUserId()).equals(guessUserId)) {
			statusCodeEnum = StatusCodeEnum.CODE100200;
			returnJsonEntity.setCode(statusCodeEnum.getCode());
			returnJsonEntity.setMsg(statusCodeEnum.getMsg());
			return returnJsonEntity;
		}
		// c
		String goodsIds = getParam("goodsIds");
		// 是否开票
		Integer isInvoice = getIntParam("isInvoice");
		String invoiceName = getParam("invoiceName");
		// 送货地址ID
		Long addressId = getLongParam("addressId");
		// 快递编号
		String expressCode = getParam("expressCode");
		double expressFee = getDoubleParam("expressFee");
		// 抵扣费用 积分数量
		Integer point = getIntParam("point");
		// 订单备注
		String remark = getParam("remark");
		if (remark == null) {
			remark = "";
		}
		/**
		 * 1=app,2=微信，3=微博,4=PC,5=H5
		 */
		Integer source = getIntParam("source");
		if (source <= 0) {
			source = 4;
		}

		// 预约联系人姓名
		String reserveUserName = getParam("userName");
		// 预约联系人电话
		String reserveMobile = getParam("mobile");
		// 预约人性别
		String reserveGender = getParam("gender");
		if (!reserveGender.equals("")) {
			reserveGender = reserveGender.equals("1") ? "男" : "女";
		}
		// 预约联系时间
		String reserveTime = getParam("reserveTime");

		int couponId = getParam("couponId", 0);
		if (!goodsIds.equals("")) {
			ReceiveOrderListModel orderData = new ReceiveOrderListModel();
			List<ReceiveOrderModel> orderCollocations = new ArrayList<>();

			String[] strGoodsIds = goodsIds.split(";");

			if (strGoodsIds.length > 0) {
				String[] strGoodsInfo;
				long sizeCode = 0;
				long goodsId = 0;
				int purchaseQuanlity = 0;
				int isPrepay = 0;
				for (int i = 0; i < strGoodsIds.length; i++) {
					strGoodsInfo = strGoodsIds[i].split(",");
					if (strGoodsInfo.length == 4) {
						isPrepay = Integer.parseInt(strGoodsInfo[1]);
						sizeCode = Long.parseLong(strGoodsInfo[2]);
						purchaseQuanlity = Integer.parseInt(strGoodsInfo[3]);
						goodsId = Long.parseLong(strGoodsInfo[0]);
						Goods goodsInfo = goodsService.selectByGoodsId(goodsId);
						GoodsSize goodsSize = goodsSizeService.selectbySizeId(sizeCode);
						if (goodsInfo != null && goodsSize != null) {
							if (goodsInfo.getTypeFlag() != 3 && goodsSize.getInventoryNum() < purchaseQuanlity) {
								statusCodeEnum = StatusCodeEnum.CODE500501;
								returnJsonEntity.setCode(statusCodeEnum.getCode());
								returnJsonEntity.setMsg("[" + goodsInfo.getTitle() + "]" + statusCodeEnum.getMsg());
								return returnJsonEntity;
							}
						} else {
							statusCodeEnum = StatusCodeEnum.CODE400404;
							returnJsonEntity.setCode(statusCodeEnum.getCode());
							returnJsonEntity.setMsg(statusCodeEnum.getMsg());
							return returnJsonEntity;
						}

						ReceiveOrderModel model = new ReceiveOrderModel();
						model.setGoodsId(strGoodsInfo[0]);
						model.setSizeCode(sizeCode+"");
						model.setQuantity(purchaseQuanlity);
						model.setIsPrepay(isPrepay);
						orderCollocations.add(model);
					}
				}
				orderData.setCouponId(couponId);
				orderData.setOrderCollocations(orderCollocations);
				orderData.setIsInvoice(isInvoice);
				orderData.setInvoiceName(invoiceName);
				orderData.setAddressId(addressId);
				orderData.setExpressCode(expressCode);
				orderData.setExpressFee(expressFee);
				orderData.setPoint(point);
				orderData.setRemark(remark);
				orderData.setReserveUserName(reserveUserName);
				orderData.setReserveMobile(reserveMobile);
				orderData.setReserveGender(reserveGender);
				orderData.setReserveTime(reserveTime);
				long userId = getTokenUserId();

				try {
					long orderId = orderService.createOrder(orderData, userId,source);
					if (orderId > 0) {
						statusCodeEnum = StatusCodeEnum.CODE000000;
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("orderId", orderId+"");
						map.put("orderJe", orderData.getOrderJe());

						returnJsonEntity.setData(map);
					} else if (orderId == -2) {
						statusCodeEnum = StatusCodeEnum.CODE700301;
					}
				} catch (Exception er) {
					log.error("createOrder error:" + er.getMessage());
				}
			}
		}

		returnJsonEntity.setCode(statusCodeEnum.getCode());
		returnJsonEntity.setMsg(statusCodeEnum.getMsg());

		return returnJsonEntity;
	}

	/**
	 * 订单状态更新
	 */
	@RequestMapping(value = "/status")
	public ReturnJsonEntity orderStatus() {
		ReturnJsonEntity returnJsonEntity = new ReturnJsonEntity();
		StatusCodeEnum statusCodeEnum = StatusCodeEnum.CODE100000;
		long orderId = getLongParam("orderId");
		// 微信支付=wxpay 支付宝支付=alipay
		String payMethod = getParam("payMethod");
		String orderStatus = getParam("oderStatus");
		String orderStatusText = getParam("oderStatusText");
		try {
			if (orderId > 0 && WechatUtil.validOrderStats(orderStatus)) {
				Order order = orderService.selectByOrderId(orderId);
				if (order != null && !order.getOderStatus().equals(orderStatus)) {
					if (orderService.updateOrderStatus(orderId, orderStatus, orderStatusText))
						statusCodeEnum = StatusCodeEnum.CODE000000;
				}
			}
		} catch (Exception er) {
			statusCodeEnum = StatusCodeEnum.CODE100000;
			log.error("订单ID:" + orderId + " 状态更新错误:" + er.getMessage());
		}

		returnJsonEntity.setCode(statusCodeEnum.getCode());
		returnJsonEntity.setMsg(statusCodeEnum.getMsg());
		return returnJsonEntity;
	}
	/**
	* <p>Title: queryorderstatus</p>
	* <p>Description: 查询订单状态/p>
	* @return 订单状态:00=待付款/10=待发货/20=已发货/30=已完成/90=订单取消
	 */
	@ResponseBody
	@RequestMapping(value = "/queryorderstatus",method = RequestMethod.GET)
	public ReturnJsonEntity queryorderstatus() {
		ReturnJsonEntity returnJsonEntity = new ReturnJsonEntity();
		StatusCodeEnum statusCodeEnum = StatusCodeEnum.CODE100000;
		//游客身份验证
		if(String.valueOf(getTokenUserId()).equals(guessUserId)){
			statusCodeEnum=StatusCodeEnum.CODE100200;
			returnJsonEntity.setCode(statusCodeEnum.getCode());
			returnJsonEntity.setMsg(statusCodeEnum.getMsg());
			return returnJsonEntity;
		}
		long orderId =  getLongParam("orderId");
		Order orderData = orderService.selectByOrderId(orderId);
		if(orderData!=null){
			String oderStatusText = orderData.getOrderStatusText();
			String oderStatus = orderData.getOderStatus();
			Map<String,String> initMap= new HashMap<String,String>();
			initMap.put("oderStatusText", oderStatusText);
			initMap.put("oderStatus", oderStatus);
			returnJsonEntity.setData(initMap);
			statusCodeEnum = StatusCodeEnum.CODE000000;
		}
		returnJsonEntity.setCode(statusCodeEnum.getCode());
		returnJsonEntity.setMsg(statusCodeEnum.getMsg());
		return returnJsonEntity;
	}
}
